package cn.itcast.service.impl;

import cn.itcast.pojo.Weather;
import cn.itcast.service.WeatherService;
import cn.itcast.utils.CityCodeUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class WeatherServiceImpl implements WeatherService {


    @Autowired
    private RestTemplate restTemplate;

    /**
     *
     * @param cityName 城市名称
     * @return 5天的城市天气信息
     */
    @Override
    public List<Weather> getCityWeatherInfo(String cityName) {
        String  code  = CityCodeUtils.getCityCode(cityName);
        String url = "http://t.weather.itboy.net/api/weather/city/"+code;
        String jsonResponse = restTemplate.getForObject(url, String.class);

        // 解析JSON数据
        JSONObject jsonObject = JSONObject.parseObject(jsonResponse);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray forecastArray = data.getJSONArray("forecast");

        // 封装未来五天的天气预报
        List<Weather> weatherList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            JSONObject forecast = forecastArray.getJSONObject(i);
            Weather weather = new Weather();
            weather.setHigh(forecast.getString("high"));
            weather.setLow(forecast.getString("low"));
            weather.setYmd(forecast.getString("ymd"));
            weather.setWeek(forecast.getString("week"));
            weather.setFx(forecast.getString("fx"));
            weather.setFl(forecast.getString("fl"));
            weather.setType(forecast.getString("type"));
            weather.setNotice(forecast.getString("notice"));
            weatherList.add(weather);
        }
        return weatherList;
    }
}
